package com.watson.todolist;

import java.security.GeneralSecurityException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.watson.todolist.database.AccountManager;
import com.watson.todolist.to.TodoListAccount;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the Registration page activity that functions to create the screen
 * that allows the user to create an account.
 * 
 * @author Jasmin Muminhodzic
 * @version 1.0
 * 
 */
public class registrationPage extends Activity {

	AccountManager accountManager;
	EditText username;
	EditText password;
	EditText confirmPassword;
	EditText email;
	Button submit;
	Button cancel;

	/**
	 * This method is called when the activity is created.
	 * 
	 * @param savedInstanceState
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.registerpagelayout);

		accountManager = AccountManager.getAccountManager();

		username = (EditText) findViewById(R.id.editText1);
		password = (EditText) findViewById(R.id.editText2);
		confirmPassword = (EditText) findViewById(R.id.editText3);
		email = (EditText) findViewById(R.id.editText4);
		submit = (Button) findViewById(R.id.registerSubmit);
		submit.setOnClickListener(registerListener);
		cancel = (Button) findViewById(R.id.registerCancel);
		cancel.setOnClickListener(cancelListener);
	}

	/**
	 * Checks if a string is a valid email address format using regular
	 * expression.
	 * 
	 * @param email
	 *            String to check email address format validity from
	 * @return true if valid email format, false otherwise
	 */
	public static boolean isValidEmail(String email) {

		String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email;

		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		if (matcher.matches()) {
			return true;
		}
		return false;
	}

	/**
	 * This functions as the listener object for the submit button. It creates a
	 * new user if the given username is available, the passwords match and are
	 * six characters or greater, and none of the fields are blank.
	 */
	private OnClickListener registerListener = new OnClickListener() {
		@Override
		public void onClick(View v) {

			// Error message set up (custom toast layout)
			// display error message to User using a custom "toast" message
			LayoutInflater inflater = getLayoutInflater();
			View toastLayout = inflater.inflate(R.layout.custom_toast,
					(ViewGroup) findViewById(R.id.custom_toast_root));
			((ImageView) toastLayout.findViewById(R.id.toastImg))
					.setImageResource(R.drawable.error_img);

			String passString = password.getText().toString();
			String confirmPassString = confirmPassword.getText().toString();
			String usernameString = username.getText().toString();
			String emailString = email.getText().toString();

			// check that none of fields are blank
			if (usernameString.equals("") || passString.equals("")
					|| emailString.equals("")) {
				// setting text of custom toast message
				((TextView) toastLayout.findViewById(R.id.toastText))
						.setText("ERROR: You must fill in all fields!");
				Toast lengthError = Toast.makeText(getApplicationContext(), "",
						4000);
				lengthError.setView(toastLayout);
				lengthError.show();
			}

			// check that password is 6 or more characters
			else if (passString.length() < 6) {
				// setting text of custom toast message
				((TextView) toastLayout.findViewById(R.id.toastText))
						.setText("ERROR: Password must be 6 or more characters in length.");
				Toast lengthError = Toast.makeText(getApplicationContext(), "",
						4000);
				lengthError.setView(toastLayout);
				lengthError.show();
			}

			// check that passwords are the same
			else if (!passString.equals(confirmPassString)) {
				// setting text of custom toast message
				((TextView) toastLayout.findViewById(R.id.toastText))
						.setText("ERROR: Passwords do not match. Please retype.");

				Toast matchError = Toast.makeText(getApplicationContext(), "",
						4000);
				matchError.setView(toastLayout);
				matchError.show();
			}

			// check if the username already exists
			else if (accountManager.userNameExistence(usernameString)) {
				// display custom error message
				((ImageView) toastLayout.findViewById(R.id.toastImg))
						.setImageResource(R.drawable.error_img);
				// setting text of custom toast message
				((TextView) toastLayout.findViewById(R.id.toastText))
						.setText("ERROR: Username already exists. Please try a different name.");

				Toast userError = Toast.makeText(getApplicationContext(), "",
						4000);
				userError.setView(toastLayout);
				userError.show();
			}

			// check if the email adress already exists
			else if (accountManager.userEmailExistence(emailString)) {
				// display custom error message
				((ImageView) toastLayout.findViewById(R.id.toastImg))
						.setImageResource(R.drawable.error_img);
				// setting text of custom toast message
				((TextView) toastLayout.findViewById(R.id.toastText))
						.setText("ERROR: Email address already exists. Please try a different email.");

				Toast userError = Toast.makeText(getApplicationContext(), "",
						4000);
				userError.setView(toastLayout);
				userError.show();
			}

			// check if valid email address
			else if (!isValidEmail(emailString)) {
				// display custom error message
				((ImageView) toastLayout.findViewById(R.id.toastImg))
						.setImageResource(R.drawable.error_img);
				// setting text of custom toast message
				((TextView) toastLayout.findViewById(R.id.toastText))
						.setText("ERROR: Please enter a valid email address.");

				Toast userError = Toast.makeText(getApplicationContext(), "",
						4000);
				userError.setView(toastLayout);
				userError.show();
			}

			// creates account
			else {
				try {
					// Create user account and get user id
					long userIdOfNewAccount = accountManager.createUserAccount(
							usernameString, emailString, passString);

					if (userIdOfNewAccount != -1) {
						// Fill TodoListAccount instance with user information
						TodoListAccount account = TodoListAccount.getInstance();
						account.setEmailAddress(emailString);
						account.setUserId(userIdOfNewAccount);
						account.setUserName(usernameString);

						Intent myIntent = new Intent(v.getContext(),
								todoListActivity.class);
						startActivity(myIntent);
					} else {
						// display custom error message
						((ImageView) toastLayout.findViewById(R.id.toastImg))
								.setImageResource(R.drawable.error_img);
						// setting text of custom toast message
						((TextView) toastLayout.findViewById(R.id.toastText))
								.setText("ERROR: Create account failed. Please try again.");

						Toast userError = Toast.makeText(
								getApplicationContext(), "", 4000);
						userError.setView(toastLayout);
						userError.show();
					}
				} catch (GeneralSecurityException e) {
					// TODO Does this catch need anything???
					e.printStackTrace();
				}
			}
		}
	};

	/**
	 * This functions as the listener object for the cancel button which returns
	 * the current view to the main login screen.
	 */
	private OnClickListener cancelListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent myIntent = new Intent(v.getContext(), mainLoginPage.class);
			startActivity(myIntent);
		}
	};
}